<?php
/**
 * 用户帐号控制器
 * 包含公共用户接口
 */

namespace app\controllers\user;

use Yii;
use yii\helpers\ArrayHelper;
use app\common\base\CommonController;
use app\modules\user\service\IdentityService;
use app\modules\user\service\AccountService;
use app\modules\user\service\RecordLoginService;

class AccountController extends CommonController
{
    /**
     * 登陆;
     */
    public function actionLogin()
    {
        $this->rules = [
            [['username', 'password'], 'required'],
            [['username', 'password'], 'string'],
        ];

        //校验格式，生成token
        $inputs = $this->validate();
        $info = parent::callModuleService('user', 'AccountService', 'login', $inputs['username'], $inputs['password']);

        //记录本次登陆相关信息
		// $ip = Yii::$app->request->userIP;
		// $from = (new RecordLoginService)::FROM;
		// parent::callModuleService('user', 'RecordLoginService', 'addOne', $inputs['userid'], $ip, array_search($inputs['type'], $from));

        return [
            'info' => $info['info'],
            'token' => $info['token'],
        ];
    }

    /**
     * 改密码;
     */
    public function actionChangepw()
    {
        $this->rules = [
            [['again_pw', 'asset_pw'], 'required'],
            [['password', 'again_pw', 'asset_pw'], 'string'],
        ];
        $inputs = $this->validate();
        
        if($inputs['again_pw'] != $inputs['asset_pw']) {
            return parent::error('ERROR_INVALID_PASSWORD_AGAIN', '两次输入的新密码不正确');
        }

        parent::callModuleService('user', 'AccountService', 'changePw', $this->userInfo->id, $inputs['asset_pw']);
        return [
            'success' => 1
        ];
    }

    /**
     * 找回密码;
     */
    public function actionFindpw()
    {
        $this->rules = [
            ['user_id', 'required'],
            ['user_id', 'string'],
        ];
        $inputs = $this->validate();
        $success = parent::callModuleService('user', 'AccountService', 'findPw', $inputs['user_id']);
        return [
            'success' => $success
        ];
    }
}
